package me.yuzho.study.concurrency;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class AttemptLocking {

    private ReentrantLock lock = new ReentrantLock();
    
    
    /**
     * 尝试获取锁，并不等待
     */
    public void untimed() {
        boolean captured = lock.tryLock();
        try {
            System.out.println("Try lock: " + captured);
        }finally {
            if(captured) lock.unlock();
        }
    }
    
    public void timed() {
        
        boolean captured = false;
        try {
            captured = lock.tryLock(2, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        
        try {
            System.out.println("Try lock in 2 seconds: " + captured);
        }finally {
            if(captured) lock.unlock();
        }
    }
    
    public static void main(String[] args) {
        
        final AttemptLocking al = new AttemptLocking();
        al.untimed();
        al.timed();
        
        new Thread() {
            { setDaemon(true);}
            
            public void run() {
                
                al.lock.lock();
                System.out.println("Lock is acquired by a daemon thread");
            }
        }.start();
        
        Thread.yield();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        al.untimed();
        al.timed();

    }

}
